<?php
namespace Helper\Controller;

use Common\Controller\ApiController;

class SuggestionController extends ApiController
{
    public function store()
    {
        $inputs = $this->request();
        $mSuggestion = D('Suggestion');
        $userId = $this->user['id'];
        if (mb_strlen($inputs['content']) < 5 || mb_strlen($inputs['content']) > 120) {
            $this->errorResponse(20003);
        }
        $inputs = array_keep($inputs, ['content', 'phone']);
        $inputs['user_id'] = $userId;
        if ($mSuggestion->create($inputs)) {
            $mSuggestion->add();
            $this->createdResponse();
        } else {
            $this->errorResponse(2004, $mSuggestion->getError());
        }
    }

    public function index()
    {
        $input = $this->request();
        $page = (int)filter($input['page'], 1);
        $perPage = (int)filter($input['per_page'], 10);
        $where = [];
        $where['user_id'] = $this->user['id'];
        $count = D('Suggestion')->where($where)->count();
        $suggestions = D('Suggestion')
            ->where($where)
            ->page($page, $perPage)
            ->order('create_time desc')
            ->select();
        $suggestions = transform('Suggestion', 'listview', $suggestions);
        $pagination = pagination($count, $perPage, $page);
        $this->response($suggestions, $pagination);
    }
    
}
